package com.example.yrdev.ordering_system.Dialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;

import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by luke on 17/11/2016.
 */

public class GetCashDialog extends Dialog {
    @InjectView(R.id.amount)EditText amount;
    @InjectView(R.id.cashTitle)TextView title;
    @InjectView(R.id.done)Button doneBut;
    @InjectView(R.id.total_price)TextView totalPrice;
    @InjectView(R.id.returnMoney)TextView returnMoneyTxt;

    Context context;

    boolean returnMoney=false;
    private GetCashListener getCashListener;
    private double itemCost;


    public interface GetCashListener{
        void payMoney(String money);
        void finishPayment();

    }


    public GetCashDialog(Context context){
        super(context);
        this.context=context;
        requestWindowFeature(Window.FEATURE_NO_TITLE);


    }

    public GetCashDialog(Context context,Double itemCost){
        super(context);
        this.context=context;
        this.itemCost=itemCost;
        GlobalFunction.printTextByTag("cost"+itemCost);
        requestWindowFeature(Window.FEATURE_NO_TITLE);


    }

    public void reset(){
        amount.setEnabled(true);
        returnMoney=false;

    }

    public void setItemCost(double itemCost) {
        this.itemCost = itemCost;
    }

    public double getItemCost() {
        return itemCost;
    }

    public void setGetCashListener(GetCashListener getCashListener) {
        this.getCashListener = getCashListener;
    }

    public void setReturnMoney(boolean returnMoney) {
        this.returnMoney = returnMoney;
    }



    public String getGetCurrentAmount() {
        return amount.getText().toString();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_cash_dialog);
        ButterKnife.inject(this);
        getWindow().setLayout(  WindowManager.LayoutParams.MATCH_PARENT,   WindowManager.LayoutParams.WRAP_CONTENT);
        if (!returnMoney){
            activateEditText();
        }

        initView();
    }

    private void initView(){
        totalPrice.setText(String.format(Locale.getDefault(),"%.2f",itemCost)+"元");
        amount.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_DONE){

                    if (amount.getText().toString().length()>0){

                        Double currentAmount=Double.valueOf(amount.getText().toString());
                        if (currentAmount<=0){
                            GlobalFunction.ToastAlert(context,"请输入收款金额");
                            return true;

                        }
                    }


                    return false;




                }

                return false;
            }
        });

        amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
             checkBalanceDifference();

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });



    }
    @OnClick(R.id.close)
    void close(){
        dismiss();

    }
    @OnClick(R.id.done)
    void confirmBalance(){

        if (checkBalanceDifference()){

            dismiss();
            GlobalFunction.ToastAlert(context,"消费成功");

            if (getCashListener!=null){
                getCashListener.finishPayment();
            }

        }else {

            GlobalFunction.ToastAlert(context,"收款金额低于商品价格，购物失败");
        }
    }


    private boolean checkBalanceDifference(){
    boolean stat=false;

        try {

            Double currentVal=Double.valueOf(amount.getText().toString());
            Double diff=currentVal-this.itemCost;
        String temp=String.format(Locale.getDefault(),"%.2f",diff);


            if (diff>=0){
                stat=true;
                returnMoneyTxt.setText("+"+temp+"元");
                returnMoneyTxt.setTextColor(ContextCompat.getColor(context,R.color.green));

            }else {
                returnMoneyTxt.setText("-"+temp+"元");
                returnMoneyTxt.setTextColor(ContextCompat.getColor(context,R.color.redColor));

            }
        }catch (Exception e){
            stat=false;
            returnMoneyTxt.setText("-");
            returnMoneyTxt.setTextColor(ContextCompat.getColor(context,R.color.blackColor));

        }



   return stat;

    }

    private   void activateEditText(){
        amount.getText().clear();
        amount.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);//直接弹出输入框\
    }
    boolean enoughMoney=false;//钱不够

    public void activateReturnMoneyMode(String returnMoney){
        GlobalFunction.printTextByTag(returnMoney);
        title.setText("找钱");
        //amount.setEnabled(false);
        Double temp=Double.valueOf(returnMoney);
        doneBut.setText("完成");
        if (temp>=0){//有找零钱
            String val="+"+ String.format(Locale.getDefault(),"%.2f",temp);
            returnMoneyTxt.setText(val);
            returnMoneyTxt.setTextColor(ContextCompat.getColor(context,R.color.green));

           // returnMoneyLayout.setVisibility(View.VISIBLE);
            amount.setVisibility(View.GONE);
            doneBut.setVisibility(View.VISIBLE);
            GlobalFunction.ToastAlert(context,"购物成功");
            enoughMoney=true;


        }else {//不够钱

//
//            String val= String.format(Locale.getDefault(),"%.2f",temp);
//          val= val.replace("-","- ");
//
//
//            returnMoneyLayout.setVisibility(View.VISIBLE);
//            amount.setVisibility(View.GONE);
//            doneBut.setVisibility(View.VISIBLE);
//
//            returnMoneyTxt.setText(val);
//            returnMoneyTxt.setTextColor(ContextCompat.getColor(context,R.color.redColor));
            GlobalFunction.ToastAlert(context,"收款金额低于商品价格，购物失败");
            dismiss();

        }


    }

    @Override
    public void show() {
        super.show();
        if (!returnMoney){
            amount.getText().clear();
        }

    }
}
